import { routerRedux } from 'dva/router';
import { stringify } from 'qs';
import { post } from '@/utils/request';
import * as api from '@/constants/api';
import * as constant from '@/constants';
import { setAuthority } from '@/utils/authority';
import { getPageQuery } from '@/utils/utils';
import { reloadAuthorized } from '@/utils/Authorized';

export default {
  namespace: 'login',

  state: {
    status: undefined,  // 登录状态
    errMsg: '', // 登录未成功时的提示消息（后台返回）
  },

  effects: {
    *login({ payload }, { call, put }) {
      const response = yield call(async ()=> post(api.LOGIN, payload));
      // 挺奇怪的，如果request发生错误（fetch），也照样会走到这里
      // 倘若是自己的post，不会走到这里
      // 按理来说，yield碰到错误之后，不会再走后面的yield了
      yield put({
        type: 'changeLoginStatus',
        payload: response,
      });

      // 登录成功，保存token，reload权限，如果有redirect，跳转到原链接
      if (response.status === 'ok') {
        localStorage.setItem(constant.STORAGE_TOKEN_KEY, response.token);
        reloadAuthorized();
        const urlParams = new URL(window.location.href);
        const params = getPageQuery();
        let { redirect } = params;
        if (redirect) {
          const redirectUrlParams = new URL(redirect);
          if (redirectUrlParams.origin === urlParams.origin) {
            redirect = redirect.substr(urlParams.origin.length);
            if (redirect.match(/^\/.*#/)) {
              redirect = redirect.substr(redirect.indexOf('#') + 1);
            }
          } else {
            redirect = null;
          }
        }
        yield put(routerRedux.replace(redirect || '/'));
      }
    },

    *logout(_, { put }) {
      yield put({
        type: 'changeLoginStatus',
        payload: {
          status: false,
          currentAuthority: 'guest',
          errMsg: '',
        },
      });
      reloadAuthorized();
      // redirect
      if (window.location.pathname !== '/user/login') {
        yield put(
          routerRedux.replace({
            pathname: '/user/login',
            search: stringify({
              redirect: window.location.href,
            }),
          })
        );
      }
    },
  },

  reducers: {
    changeLoginStatus(state, { payload }) {
      setAuthority(payload.currentAuthority);
      return {
        ...state,
        status: payload.status,
        errMsg: payload.errMsg,
      };
    },
  },
};
